package com.hm.PushCaseService.service.push.qycg.login;

import com.hm.PushCaseService.constant.ReqUrl;
import com.hm.PushCaseService.constant.UserInfo;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LoginCookieService implements ILoginCookie {
    private static final Logger logger = LoggerFactory.getLogger(LoginCookieService.class);

    //获取cookies
    private static final String CookieUrl = ReqUrl.LoginUrl + "?" + "userAccount=" + UserInfo.UserAccount + "&" + "userPassword=" + UserInfo.UserPassword;

    @Qualifier("OkHttpClient")
    public OkHttpClient okHttpClient;

    public LoginCookieService(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    @Override
    public String getCookie() {
        Request request = new Request.Builder().url(CookieUrl).build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            ResponseBody body = response.body();
            if (body == null) {
                logger.error("获取cookie失败：body为空");
                return "";
            }
            String res = body.string();
            if (res.contains("true")) {
                //登陆成功
                Headers headers = response.headers();
                List<String> cookies = headers.values("Set-Cookie");
                if (!cookies.isEmpty()) {
                    String s = cookies.get(0);
                    String[] s1 = s.trim().replaceAll(" ", "").split(";");
                    return s1[0];
                } else {
                    logger.error("获取cookie为空");
                }
            } else {
                //登陆失败
                logger.error("获取cookie失败（非登录状态）：ResponseBody:" + res);
            }
        } catch (Exception e) {
            logger.error("获取cookie失败：Exception:" + e.getMessage());
        }
        return "";
    }

}
